package com.spider.admin.service.service;

import com.spider.admin.conf.ResultMessage;
import com.spider.admin.conf.validator.Constants;
import com.spider.admin.exception.SpiderException;
import com.spider.admin.http.entity.PageResult;
import com.spider.admin.service.async.AsyncService;
import com.spider.admin.store.primary.mapper.AppMapper;
import com.spider.admin.store.primary.mapper.ClientMapper;
import com.spider.admin.store.primary.mapper.ServiceMapper;
import com.spider.admin.store.primary.model.AppInfo;
import com.spider.admin.store.primary.model.ServiceInfo;
import com.spider.admin.utils.CommonUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;


@Slf4j
@org.springframework.stereotype.Service
public class ServiceImpl implements Service {

    @Autowired
    private ServiceMapper serviceMapper;


    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private AppMapper appMapper;

    @Resource
    private AsyncService asyncService;


    @Override
    public ServiceInfo queryServiceById(String pid) throws SpiderException {
        return serviceMapper.queryServiceById(pid);
    }

    @Override
    public int saveService(ServiceInfo serviceInfo) throws SpiderException {
        serviceInfo
                .setLineStatus(Constants.OFFLINE.getCode())
                .setPid(CommonUtil.getShortUniqueId());
        String clientId = serviceInfo.getPublishClientId();
        long count = -1;
        if (StringUtils.isNotEmpty(clientId)) {
            count = clientMapper.getActiveClientCountById(clientId);
            if (count <= 0) {
                throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "客户端未激活或不存在");
            }
        }

        AppInfo appInfo = appMapper.queryAppById(serviceInfo.getAppId());
        if (appInfo == null || "archive".equals(appInfo.getAppStatus())) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "应用未激活或不存在");
        }
        serviceInfo.setServiceUrl(appInfo.getAppUri() + serviceInfo.getServiceUri());
        int i = serviceMapper.saveService(serviceInfo);
//        log.info("新注册服务：{}", serviceInfo.getServiceName());
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }

    @Override
    public int updateService(ServiceInfo serviceInfo, String pid) throws SpiderException {
        serviceInfo.setLineStatus(null);
        AppInfo appInfo = appMapper.queryAppById(serviceInfo.getAppId());
        if (appInfo == null || "archive".equals(appInfo.getAppStatus())) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "应用未激活或不存在");
        }
        serviceInfo.setServiceUrl(appInfo.getAppUri() + serviceInfo.getServiceUri());
        int i = serviceMapper.updateService(serviceInfo, pid);
//        log.info("更新服务信息：{}", pid);
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }

    @Override
    public int onLineService(String pid) throws SpiderException {
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setLineStatus(Constants.ONLINE.getCode());
        int i = serviceMapper.updateService(serviceInfo, pid);
//        log.info("激活服务：{}", pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public int offLineService(String pid) throws SpiderException {
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setLineStatus(Constants.OFFLINE.getCode());
        int i = serviceMapper.updateService(serviceInfo, pid);
//        log.info("归档服务：{}", pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public PageResult<ServiceInfo> queryServiceByTenantId(Integer page,
                                                          Integer pageSize,
                                                          String serviceName,
                                                          String curTenantId,
                                                          String tenantId,
                                                          String appId) throws SpiderException {

        page = page == null || page.intValue() <= 0 ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        long totalCount = serviceMapper.getServiceRecordNumByTenantId(curTenantId, tenantId, serviceName, appId).longValue();

        int totalPage = (int) Math.ceil((double) totalCount / (double) pageSize);
        page = page > totalPage ? totalPage : page;
        page = page <= 0 ? 1 : page;
        PageResult<ServiceInfo> result = new PageResult<>();
        result.setCurrentPage(page);
        result.setPageSize(pageSize);
        result.setTotal(totalCount);
        result.setTotalPage(totalPage);

        List<ServiceInfo> records = serviceMapper.queryServiceListByTenantId((page - 1) * pageSize, pageSize, curTenantId, tenantId, serviceName, appId);
        result.setList(records);

        return result;
    }

    @Override
    public int remove(String pid) throws SpiderException {
        int i = serviceMapper.remove(pid);
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }
}

